﻿using System;
using System.Collections;
using System.Collections.Generic;
using System.Configuration;
using System.IO;
using System.Linq;
using System.Net;
using System.Net.Sockets;
using System.Text;
using System.Threading;
using TOOLS;
using BLL;
namespace KMServer
{
    public class ClientHandle
    {
        delegate void ProcesssRequst(TcpClient tcpClient);
        private static string GetAppConfig(string strKey)
        {
            foreach (string key in ConfigurationManager.AppSettings)
            {
                if (key == strKey)
                {
                    return ConfigurationManager.AppSettings[strKey];
                }
            }
            return null;
        }
        public bool enableListenr = false;
        string m_serverIP = GetAppConfig("localIp");
        int m_port = GetAppConfig("port").ToInt();
        TcpListener m_Listener = null;
        IPAddress m_host=null;
        private string m_returnData, m_sendData;
        byte[] data;
      
        Thread thListener = null;
        Thread thCheckListener = null;
        public Queue<string> clientLogQueue = new Queue<string>();
        public  void EnLog(string value, params object[] args)
        {
                clientLogQueue.Enqueue(DateTime.Now.ToString() + "  " + string.Format(value, args));
        }
        public  string DeLog()
        {
            if (clientLogQueue.Count > 0)
            {
                return clientLogQueue.Dequeue();
            }
            return null;
        }
       
        Dictionary<string, Dictionary<string, string>> returnMsg = new Dictionary<string, Dictionary<string, string>>();
        List<string> loginGuid = new List<string>();
        
        public void Listener()
        {
          
            try
            {
                m_host = IPAddress.Parse(m_serverIP);
                m_Listener = new TcpListener(m_host, m_port);
                m_Listener.Start();
                EnLog("服务启动.....");
                while (enableListenr)
                {
                    TcpClient tcpClient = m_Listener.AcceptTcpClient();
                    ProcesssRequst process = new ProcesssRequst(ResponseClient);
                    process.BeginInvoke(tcpClient,null,null);
                }
                m_Listener.Stop();
                EnLog("服务中止.....");
            }
            catch (Exception e)
            {
               EnLog( "-----Listener-----" + e.Message);
            }
        }
        public void Start()
        {
            enableListenr = true;
            thCheckListener = new Thread(CheckListener);
            thCheckListener.IsBackground = true;
            thCheckListener.Start();

        }
        void CheckListener()
        {
            while (enableListenr)
            {
                if (thListener == null || !thListener.IsAlive)
                {
                    thListener = new Thread(Listener);
                    thListener.IsBackground = true;
                    thListener.Start();
                }
                Thread.Sleep(1000);
            }
        }
        public void Stop()
        {
            enableListenr = false;
            m_Listener.Stop();
        }
        byte[] EncodingUTF8(string buf)
        {
            byte[] data = Encoding.UTF8.GetBytes(buf + "\r\n");
            return data;
        }

        public void ResponseClient(TcpClient tcpClient)
        {
            if (tcpClient != null)
            {
                try
                {
                    using (StreamReader rs = new StreamReader(tcpClient.GetStream()))
                    {
                        using (NetworkStream ws = tcpClient.GetStream())
                        {
                            while (enableListenr)
                            {
                                m_returnData = rs.ReadLine();
                                m_returnData = m_returnData.DESDecrypt();
                                m_sendData = (MsgProc(m_returnData.StringToDictionary())).DictionaryToString();
                                m_sendData = m_sendData.DESEncrypt();
                                data = EncodingUTF8(m_sendData);
                                ws.Write(data, 0, data.Length);
                                Thread.Sleep(100);
                            }
                        }
                    }
                }
                catch (Exception e)
                {
                    EnLog("-----ResponseClient-----" + e.Message);
                    return;
                }
            }
        }
        LogicAPI bllLogicApi = new LogicAPI();
        public Dictionary<string,string> MsgProc(Dictionary<string, string> p)
        {
            Dictionary<string, string> result = new Dictionary<string, string>();
            
            object temp= bllLogicApi.RunMethod(p["proc"], new object[] { p });
            if (temp != null)
            {
                result = (Dictionary<string, string>)temp;
                result.Add("msg_key", p["msg_key"]);
            }
            else
            {
                result.Add("msg_key", p["msg_key"]);
                result.Add("status", "无处理过程" + p["proc"]);
                result.Add("message", "无处理过程" + p["proc"]);
              
            }
            return result;
        }
    }

}
